<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminController as Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

use App\Model\User;
use App\Model\Admin;

class ProfileController extends Controller{
    protected $valid = [
        'oldpasswd' => 'required',
        'passwd' => ['required',],
        'repasswd' => ['required',"same:passwd"],
    ];

    /**
     * 修改管理员个人资料
     * @author liuchang
     */
    public function edit($id){
        if(request()->isMethod('post')){
            $this->validate(request(), $this->valid);
            $param = request()->only(['oldpasswd', 'passwd', 'repasswd']);
            $admin = DB::table('admin')->where('id',$id)->first();
            if( empty($admin) || encode_passwd($param['oldpasswd'])!=$admin->passwd ){
                return back()->withErrors('原密码不对')->withInput();
            }
            $data = [
                'passwd'=>encode_passwd($param['passwd']),
            ];
            if( DB::table('admin')->where('id',$id)->update($data) ){
                return back()->withSuccess('修改成功')->withInput();
            }
            return back()->withErrors('修改失败')->withInput();
        }
        
        $data = User::find($this->admin['id']);
        return view('Admin.Profile.edit')->with('data', $data);
    }

    /**
     * 刷新（权限修改后使用，不用重新登录）
     * @author youjiahua
     */
    public function refresh(){

        $admin = Admin::get_admin_info($this->admin['id']);
        session()->forget('admin');
        session()->put([
            'admin' => [
                'id' => $admin['id'],
                'name' => $admin['username'],
                'rights' => $admin['rights'],
                'article_cats'=>empty($admin['article_cats'])?[]:json_decode($admin['article_cats']),
                'video_cats'=>empty($admin['video_cats'])?[]:json_decode($admin['video_cats']),
            ]
        ]);
        return redirect('/');
    } 
}
